package cn.deepmax.spring.cloud.system.user.controller;

import cn.deepmax.spring.cloud.common.web.AjaxResponse;
import cn.deepmax.spring.cloud.system.user.entity.User;
import cn.deepmax.spring.cloud.system.user.mapper.UserMapper;
import cn.deepmax.spring.cloud.system.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Around;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    Environment environment;
    @Autowired
    UserMapper userMapper;


    @GetMapping("index.json")
    public AjaxResponse user(){
        return AjaxResponse.ok(getEnv());
    }


    @GetMapping("/{id}.json")
    public AjaxResponse getUser(HttpServletRequest request, @PathVariable(name = "id") Long id){
        log.info("Get request from {}, id {}", request.getSession().getId(), id);
        Optional<User> user = userService.findUser(id);
        if(user.isPresent())
            return AjaxResponse.ok(user.get());
        else
            return AjaxResponse.fail("user not found");
    }


    @PostMapping("/add.json")
    public AjaxResponse addUser(@RequestParam String name, @RequestParam String password){
        Boolean ok = userService.addUser(name, password);
        if(ok)
            return AjaxResponse.ok("ok");
        else
            return AjaxResponse.fail("添加失败");
    }

    @PostMapping("/login.json")
    public AjaxResponse userLogin(@RequestParam String name, @RequestParam String password){
        Boolean ok = userService.login(name, password);
        if(ok)
            return AjaxResponse.ok("loginOK");
        else
            return AjaxResponse.fail("loginFail");
    }

    @GetMapping("/list.json")
    public AjaxResponse userList(String name,String pass,String orderBy){
        List<User> allByName = userMapper.findAllByName(name, pass, orderBy);
        return AjaxResponse.ok(allByName);
    }

    private String getEnv(){
        return environment.getProperty("my.pro");
    }


}
